<template>
  <div id="labTatRules">
    <Breadcrumb content="TAT基础规则设置" />
    <div class="bodyContent">
      <!-- vxe-toolbar -->
      <Splitpanes class="area">
        <Pane size="25">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-button type="text" icon="vxe-icon-refresh" content="刷新" :loading="saveLoading" class="button-blue margin-left-sm" @click="findLabTatBaseruleList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addNewEvent"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-edit" content="编辑" @click="editEvent"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-save" content="删除" class="button-red margin-left-sm" @click="handleDelete"></vxe-button>
            </template>
          </vxe-toolbar>
          <vxe-table border show-overflow keep-source ref="ruleNodeTableRef" v-loading="loading" height="auto" @current-change="rowClick" :column-config="{ resizable: true }" :row-config="{isCurrent:true}" :data="tatRuleListNodes">
            <vxe-column field="seq" title="#" width="30" type="seq" align="center"></vxe-column>
            <vxe-column field="baseruleNo" title="编号" width="80px">
              <template #default="{ row }">
                {{ row.baseruleNo }}
              </template>
              <template #edit="{ row }">
                <vxe-input v-model="row.baseruleNo" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="baseruleNa" title="TAT基础规则名称" min-width="180px">
              <template #default="{ row }">
                {{ row.baseruleNa }}
              </template>
              <template #edit="{ row }">
                <vxe-input v-model="row.baseruleNa" type="text"></vxe-input>
              </template>
            </vxe-column>
          </vxe-table>
        </Pane>
        <Pane size="30">
          <el-tabs type="border-card">
            <el-tab-pane label="属性信息">
              <LabTatBaseRulesForm ref="LabTatBaseRulesFormRef" @changeEvent="reClacCombineArr" />
            </el-tab-pane>
            <ExtraPropertyPanel :busRow="curSlectRow" />
          </el-tabs>
        </Pane>
        <Pane size="45">
          <vxe-toolbar>
            <template #buttons>
              <span></span>
            </template>
            <template #tools>
              <div class="margin-right-xs">
                <vxe-button type="text" class="button-blue" icon="vxe-icon-edit" content="保存" @click="saveTatBaseRuleList"></vxe-button>
                <vxe-button type="text" class="button-red" icon="vxe-icon-edit" content="删除" @click="deleteTatBaseRuleList"></vxe-button>
              </div>
            </template>
          </vxe-toolbar>
          <div class="tableBox-right">
            <vxe-table border ref="tableRef" height="auto" :column-config="{ resizable: true }" :row-config="{isCurrent:true}" :data="tatBaseRuleList">
              <vxe-column type="checkbox" width="30" align="center"></vxe-column>
              <vxe-column type="seq" width="30"></vxe-column>
              <vxe-column width="30" align="center">
                <template #default="{row}">
                  <span>{{row&&(row.id==''||row.id===null||row.id===undefined)?'-':''}}</span>
                </template>
              </vxe-column>
              <vxe-column field="name" title="TAT监控节点名称" min-width="180px">
                <template #default="{row}">
                  <div class="text-bold text-shadow text-14">{{row.tatNodeNa}}</div>
                  <div>
                    <span>{{`${row.nodeStartNa}`}}</span>
                    <span class="margin-lr-sm">至</span>
                    <span>{{`${row.nodeEndNa}`}}</span>
                  </div>
                </template>
              </vxe-column>
              <vxe-column field="patTypeNa" title="病人类型" width="80px">
                <template #default="{row}">
                  <span>{{`${row.patType} ${row.patTypeNa}`}}</span>
                </template>
              </vxe-column>
              <vxe-column field="isUrgent" title="是否急诊" width="80px" align="center">
                <template #default="{row}">
                  <span>{{row.isUrgent===0?'否':'是'}}</span>
                </template>
              </vxe-column>
              <vxe-column field="sampleTypeNa" title="样本类型" width="80px">
                <template #default="{row}">
                  <span>{{`${row.sampleType} ${row.sampleTypeNa}`}}</span>
                </template>
              </vxe-column>
              <vxe-column field="barcodeTypeNa" title="分管类别" width="80px">
                <template #default="{row}">
                  <span>{{`${row.barcodeType} ${row.barcodeTypeNa}`}}</span>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>

      </Splitpanes>
    </div>
    <vxe-modal v-model="isVisiable" width="55vw" :loading="showLoading" show-footer destroy-on-close :mask="false">
      <template #title>
        <span class="text-bold">TAT基础规则新增/编辑</span>
      </template>
      <template #default>
        <div>
          <vxe-form :data="bacTestResultForm" title-width="85px">
            <vxe-form-gather span="8">
              <vxe-form-item title="编号" field="baseruleNo" span="24">
                <template #default="params">
                  <vxe-input v-model="params.data.baseruleNo" type="text" placeholder="编号" clearable></vxe-input>
                </template>
              </vxe-form-item>
            </vxe-form-gather>
            <vxe-form-gather span="8">
              <vxe-form-item title="排序码" field="seq" span="24">
                <template #default="params">
                  <vxe-input v-model="params.data.seq" type="text" placeholder="排序码" clearable></vxe-input>
                </template>
              </vxe-form-item>
            </vxe-form-gather>
            <vxe-form-gather span="8">
              <vxe-form-item title="是否启用" field="isEnable" span="24">
                <template #default="params">
                  <vxe-switch v-model="params.data.isEnable" :close-value="0" :open-value="1" size="medium" open-label="是" close-label="否"></vxe-switch>
                </template>
              </vxe-form-item>
            </vxe-form-gather>
            <vxe-form-gather span="24">
              <vxe-form-item title="名称" field="baseruleNa" span="24">
                <template #default="params">
                  <vxe-input v-model="params.data.baseruleNa" type="text" placeholder="名称" clearable></vxe-input>
                </template>
              </vxe-form-item>
            </vxe-form-gather>
            <vxe-form-gather span="24">
              <vxe-form-item title="备注" field="remark" span="24" :item-render="{}" title-overflow="ellipsis">
                <template #default="params">
                  <vxe-textarea v-model="params.data.remark" placeholder="备注" :autosize="{ minRows: 18, maxRows: 20 }" resize="vertical"></vxe-textarea>
                </template>
              </vxe-form-item>
            </vxe-form-gather>
          </vxe-form>
        </div>
      </template>
      <template #footer>
        <vxe-toolbar>
          <template #buttons>
          </template>
          <template #tools>
            <vxe-button type="text" class="button-white" @click="isVisiable=false">取消</vxe-button>
            <vxe-button type="text" class="button-blue" @click="handleSaveOrUpdate">确定</vxe-button>
          </template>
        </vxe-toolbar>
      </template>
    </vxe-modal>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========src\views\lab_sys\bac_set\BacGermDict.vue
import Breadcrumb from '../../../components/Breadcrumb.vue'; //面包屑
import { reactive, ref, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import XEClipboard from 'xe-clipboard';
import LabTatBaseRulesForm from './LabTatBaseRulesForm.vue'; //基本信息表单组件
import ExtraPropertyPanel from '@/components/ExtraPropertyPanel.vue';
import { IsEmpty } from '@/utils/common';
import { AppStore } from '@/stores/store';

let store = AppStore();
// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();

/**弹窗编辑 */
let isVisiable = ref(false);

/**TAT基础规则表单 */
let bacTestResultForm = reactive({
  id: '',
  seq: 1,
  baseruleNo: '',
  baseruleNa: '',
  remark: '',
  isEnable: 1
});

// 获取屏幕宽度
let conWidth = ref(document.documentElement.clientWidth);

// 页面标题
const LabTatBaseRulesFormRef = ref(null);/**右侧表单对象 */
let content = ref('TAT时间规则设置');
const searchForm = reactive({ keywords: '' });/**用户输入关键字 */
let showLoading = ref(false); /**加载中 loading效果状态 */
let saveLoading = ref(false); //保存
let tatBaseRuleLoading = ref(false);/**保存明细加载中 */
let loading = ref(false); //保存
let tatBaseRuleList = reactive([]);/**基础规则 */
const ruleNodeTableRef = ref(null);/**监控节点列表对象 */
const tableRef = ref(null); //表格ref标记
const refUnqualifiedReason = ref<InstanceType<typeof refUnqualifiedReason>>(); //属性信息表单标记ref
let currentRow: any = reactive({ id: '', code: '' }); //基本信息表单当前行数据
let rowdata = {}; //点击当前行的数据
let rowIndexClick = 0; //点击当前行下标
let tatRuleListNodes: any = reactive([]);/**模块功能表格数据 */
const curSlectRow = ref({});

// 方法定义区 =============
onMounted(() => {
  findLabTatBaseruleList();
});



//查询
function findLabTatBaseruleList() {
  tatRuleListNodes.length = 0;
  loading.value = true;
  const url = '/api/lab-tat-baserule/findLabTatBaseruleList';
  proxy.$http
    .get(url)
    .then((res: any) => {
      tatRuleListNodes.length = 0;
      if (res.status.code === 1) {
        tatRuleListNodes.push(...res.data);
        if (tatRuleListNodes.length > 0) {
          rowClick({
            row: tatRuleListNodes[0],
            rowIndex: 0
          });
          ruleNodeTableRef.value?.setCurrentRow(tatRuleListNodes[0]);
        }
      }

      loading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      loading.value = false;
    });
}

function rowClick({ row, rowIndex }: any) {
  rowIndexClick = rowIndex;
  rowdata = row;
  loading.value = false;
  const $ruleNodeTableRef = proxy.$refs.ruleNodeTableRef;
  if ($ruleNodeTableRef) {
    $ruleNodeTableRef.setCurrentRow(row);
  }
  loadTatBaseRuleDetailList();
}

/**清空表单 */
function clearFormData() {
  bacTestResultForm.id = '';
  bacTestResultForm.seq = 1;
  bacTestResultForm.baseruleNo = '';
  bacTestResultForm.baseruleNa = '';
  bacTestResultForm.remark = '';
  bacTestResultForm.isEnable = 1;
}

//新增
function addNewEvent() {
  clearFormData();
  let num = tatRuleListNodes.length + 1;
  bacTestResultForm.seq = num ?? 0;
  isVisiable.value = true;
}
//保存
function handleSave() {
  if (tatRuleListNodes.length === 0) {
    VxeMessage('请维护基础规则', VxeNotifyType.error);
  } else {
    saveLoading.value = true;
    const url = '/api/lab-tat-baserule/addOrUpdateBaserule';
    proxy.$http
      .post(url, tatRuleListNodes)
      .then((res: any) => {
        VxeMessage('保存成功', VxeNotifyType.success);
        findLabTatBaseruleList();
      })
      .catch((err: any) => {
        VxeMessage('保存失败', VxeNotifyType.success);
      });
    setTimeout(() => {
      saveLoading.value = false;
    }, 500);
  }
}

/**编辑 */
function editEvent() {
  const row = ruleNodeTableRef.value?.getCurrentRecord();
  if (!row || IsEmpty(row.id)) {
    VxeMessage('请选择一行数据', VxeNotifyType.warning);
    return;
  }
  clearFormData();
  Object.assign(bacTestResultForm, row);
  isVisiable.value = true;
}

/**保存 */
function handleSaveOrUpdate() {
  showLoading.value = true;
  let url = '/api/lab-tat-baserule/addLabTatBaserule';
  if (!IsEmpty(bacTestResultForm.id)) {
    url = '/api/lab-tat-baserule/updateLabTatBaserule';
  }
  proxy.$http
    .post(url, bacTestResultForm)
    .then((res: any) => {
      VxeMessage('保存成功', VxeNotifyType.success);
      findLabTatBaseruleList();
      showLoading.value = false;
    })
    .catch((err: any) => {
      showLoading.value = false;
      VxeMessage('保存失败', VxeNotifyType.success);
    });
}
/**刪除*/
function handleDelete() {
  if (rowdata.id === '') {
    //没有做存储时，直接删除当前新增的列
    tatRuleListNodes.splice(rowdata.seq - 1, 1);
    return;
  }
  //凡是存储到库中的数据则需要清除库中的数据
  proxy.$http
    .post('/api/lab-tat-baserule/deleteLabTatBaserule', { id: rowdata.id })
    .then((res: any) => {
      if (res.status.code === 1) {
        // findItemDictRefer();
        VxeMessage('删除成功', VxeNotifyType.success);
        findLabTatBaseruleList();
      } else {
        return;
      }
    })
    .catch((err: any) => {
      VxeMessage('删除异常', VxeNotifyType.error);
    });
}

// 表格选中当前行
function tableCellClick({ row }: any) {
  curSlectRow.value = row;
  Object.assign(currentRow, row);
  proxy.$forceUpdate();
}

// 新增
function handleAdd() {
  const $formRef = refUnqualifiedReason.value;
  refUnqualifiedReason.value.addNew();
}

//保存
function saveList() {
  const $formRef = refUnqualifiedReason.value;
  refUnqualifiedReason.value.saveForm();
}

/**重新计算组合 */
function reClacCombineArr(obj: any) {
  let resultArr = [];
  const row = ruleNodeTableRef.value?.getCurrentRecord();
  for (let index = 0; index < obj.tatNodeArr.value.length; index++) {
    const element = obj.tatNodeArr.value[index];
    for (const item2 of obj.patTypeArr.value) {
      for (const item3 of obj.isUrgentArr.value) {
        for (const item4 of obj.sampleTypeArr.value) {
          for (const item5 of obj.barCodeTypeArr.value) {
            /**先查询列表中有没有，有则跳过，无则添加 */
            const arr1 = tatBaseRuleList.filter(p => p.tatNodeNo === element.tatNodeNo && p.patType === item2.code && p.isUrgent === item3.code && p.sampleType === item4.sampleType && p.barcodeType === item5.barcodeType);
            if (!arr1 || arr1.length <= 0) {
              resultArr.push({
                id: '',
                tatNodeId: element.id,
                tatNodeNo: element.tatNodeNo,
                tatNodeNa: element.tatNodeNa,
                patType: item2.code,
                patTypeNa: item2.name,
                isUrgent: item3.code,
                sampleType: item4.sampleTypeCode,
                sampleTypeNa: item4.sampleTypeName,
                barcodeType: item5.barcodeNo,
                barcodeTypeNa: item5.barcodeNa,
                tatBaseruleId: row && !IsEmpty(row.id) ? row.id : null,
                tatBaseruleNo: row && !IsEmpty(row.id) ? row.tatBaseruleNo : null,
                nodeStartNa: element.nodeStartNa,
                nodeEndNa: element.nodeEndNa,
                nodeStartNo: element.nodeStartNo,
                nodeEndNo: element.nodeEndNo
              });
            }
          }
        }
      }
    }
  }

  Object.assign(tatBaseRuleList, resultArr);
}

/**保存TAT基础规则明细 */
function saveTatBaseRuleList() {
  const arr = tatBaseRuleList.filter(p => IsEmpty(p.id));
  tatBaseRuleLoading.value = true;
  if (arr && arr.length > 0) {
    const url = '/api/lab-tat-baserule-detail/addLabTatBaseruleDetailList';
    proxy.$http
      .post(url, arr)
      .then((res: any) => {
        VxeMessage('保存成功', VxeNotifyType.success);
        tatBaseRuleLoading.value = false;
      })
      .catch((err: any) => {
        VxeMessage('保存失败', VxeNotifyType.success);
        tatBaseRuleLoading.value = false;
      });
  }
  else {
    tatBaseRuleLoading.value = false;
  }
}

/**加载TAT基础规则明细 */
function loadTatBaseRuleDetailList() {
  const row = ruleNodeTableRef.value?.getCurrentRecord();
  tatBaseRuleList.length = 0;
  proxy.$http
    .get('/api/lab-tat-baserule-detail/findLabTatBaseruleDetailList', { params: { tatBaseruleId: row.id } })
    .then((res: any) => {
      if (res.status.code === 1) {
        // findItemDictRefer();
        Object.assign(tatBaseRuleList, res.data);
      } else {
        return;
      }
    })
    .catch((err: any) => {
      //todo
    });
}

/**删除明细 */
async function deleteTatBaseRuleList() {
  const arr = await tableRef.value?.getCheckboxRecords(true);
  if (!arr || arr.length <= 0) {
    VxeMessage('请勾选要删除的', VxeNotifyType.info);
    return;
  } else {
    proxy
      .$confirm('确定删除选中数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const url = '/api/lab-tat-baserule-detail/deleteLabTatBaseruleDetailList';
        proxy.$http
          .post(url, arr)
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('删除成功', VxeNotifyType.success);
              loadTatBaseRuleDetailList();
            } else {
              VxeMessage('删除失败', VxeNotifyType.error);
            }
          })
          .catch((err: any) => {
            // VxeMessage('删除异常', VxeNotifyType.error);
          });
      });
  }
}
</script>
<style lang="scss" scoped>
#labTatRules {
  width: 100%;
  height: 100%;

  .bodyContent {
    // 面包屑40px  上下间距10px
    height: calc(100% - 60px);

    .area {
      background-color: $base-white;

      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }

      .tableBox {
        height: calc(100%);
      }

      .tableBox-right {
        height: calc(100% - 40px);
      }

      .el-tabs--border-card {
        border: none;
        height: 100%;

        :deep(.el-tabs__content) {
          height: calc(100% - 39px - 30px);
          margin: 5px 5px !important;
          .el-tab-pane {
            height: 100%;
          }
        }
      }
    }
  }
}
:deep(.el-tabs__content) {
  padding: 0 !important;
}

:deep(.el-row) {
  margin-left: 0 !important;
  margin-right: 0px !important;
}
</style>